<?php


namespace App\Admin\Controllers;

use App\Models\LiveMeetingRoom;
use App\Models\LiveMeetingRoomUser;
use App\Models\SystemRegion;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Show;
use Dcat\Admin\Controllers\AdminController;
use Dcat\Admin\Widgets\Alert;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;


class MeetingController extends AdminController
{
    /**
     * 进入会议直播间
     * 当前页面必须为https访问，否则无法申请浏览器摄像头、麦克风权限
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $errorInfo = '';
        $admin_id = Admin::user()->getKey();
        $meeting_id = request()->live_meeting_id;

        $roomInfo = LiveMeetingRoom::find($meeting_id);
        if (!$roomInfo) {
            $errorInfo = '房间未找到';
        }
        if ($roomInfo->live_admin_id != $admin_id) {
            $errorInfo = '您不是该房间的创建人，暂无权限进入';
        }
        if ($roomInfo->status == 1) {
            $errorInfo = '视频会议正在进行中，请通过APP进入观看。';
        }
        if ($errorInfo) {
            return $content->body(function (Row $row) use ($errorInfo) {
                $row->column(12, Alert::make($errorInfo, '进入失败'));
            });
        }

        if (!$roomInfo->token || strtotime($roomInfo->token_expiration_time) < time()) {
            // 重新获取token
            $effectiveTimeInSeconds = 86400;
            $roomInfo->token = get_zego_token($roomInfo->room_no, $roomInfo->room_user_no, $effectiveTimeInSeconds); // 即构token
            $roomInfo->token_expiration_time = date('Y-m-d H:i:s', time() + $effectiveTimeInSeconds);
        }
        $roomInfo->status = 1; // 开启直播
        $roomInfo->save();

        $data = [
            'roomInfo' => $roomInfo,
            'appId' => config('zego.zego_appid'),
            'server' => config('zego.zego_server'),
            'inviteTap' => '【晋乡通】「'.$roomInfo->room_name.'」复制这段内容打开“晋乡通”APP，即可加入会议。#'.$roomInfo->room_no.'#'.$roomInfo->room_secret
        ];

        return $content
            ->header('会议直播间')
            ->body(function (Row $row) use ($data) {
            $tapInfo = '会议连线过程中请勿关闭或离开本页面。(离开或关闭将导致会议结束)';
            $row->column(12, Alert::make($tapInfo, '提示')->info());
            $row->column(12, view('admin.meeting.meeting', $data));
        });
    }

    /**
     * 获得直播间在线用户
     * @param Request $request
     * @return false|string
     */
    public function ajax_get_room_user(Request $request)
    {
        $roomId = $request->input('room_id');

        $room = LiveMeetingRoom::where('room_no', $roomId)->first();
        if (empty($room) || $room->status == 0) {
            return jsonError('会议不存在或已结束');
        }

        $roomUser = LiveMeetingRoomUser::where('meeting_id', $room->id)
            ->where('status', 1)
            ->with(['user_info' => function($query){
                $query->select('id', 'user_name', 'real_name', 'head_portrait', 'region_code');
            }])
            ->orderBy('last_login_time', 'asc')
            ->get(['id', 'meeting_id', 'user_id', 'room_user_no', 'mike_status', 'last_login_time', 'token', 'audio_publish_stream_id']);

        foreach ($roomUser as &$roomUserVal) {
            $roomUserVal->last_login_time = date('H:i:s', strtotime($roomUserVal->last_login_time));
            if ($roomUserVal->user_info) {
                $roomUserVal->user_info->head_portrait = img_url($roomUserVal->user_info->head_portrait);
                $roomUserVal->user_info->user_name = $roomUserVal->user_info->real_name ?: $roomUserVal->user_info->user_name;
            }
        }

        return jsonSuccess(['user_num' => count($roomUser), 'user_list' => $roomUser]);
    }

    /**
     * 踢出房间用户
     * @param Request $request
     * @return false|string
     */
    public function ajax_out_user(Request $request)
    {
        $roomId = $request->input('room_id');
        $userNo = $request->input('user_no');
        $roomUser = LiveMeetingRoomUser::where('room_no', $roomId)->where('room_user_no', $userNo)->first();
        if (!$roomUser) {
            return jsonError('成员未找到');
        }

        $roomGetout = LiveMeetingRoomUser::roomGetOut($roomId, [$userNo]);

        if($roomGetout){
            if ($roomUser) {
                $roomUser->status = 2; // 踢出
                $roomUser->save();

                // 房间在线人数修改
                $count = LiveMeetingRoomUser::where('room_no',$roomId) ->where('status',1) -> count();
                LiveMeetingRoom::where('room_no',$roomId) -> update(['online_user_num' => $count]);
            }

            return jsonSuccess('踢出成功');
        }
    }

    /**
     * 结束会议
     * @param Request $request
     * @return false|string
     */
    public function ajax_end_meeting(Request $request)
    {
        $meetingRoomId = $request->input('meeting_room_id');
        $meeting = LiveMeetingRoom::find($meetingRoomId);
        if ($meeting) {
            $meeting->status = 0; // 结束会议
            $meeting->save();
        }

        return jsonSuccess('成功');
    }
}